<template>
	<view class="publish" @click="emojiShow =false">
		<textarea class="publish-input" v-model="form.Content" :auto-height="true" height="400" :maxlength="maxlength"
			:placeholder="$t('home.pub_tips')" @input="actInput" @blur="textblur"/>
		<view class="publish-images" v-if="!showUploadList">
			<template v-for="(item, index) in fileList">
				<view class="publish-images_item" :data-index="index" @click.stop="actPreviewImage">
					<view @click.stop="deleteItem(index)">
						<u-icon width="42" height="42" name="close-circle-fill" color="#fa3534" size="42"></u-icon>
					</view>
					<u-image width="118rpx" height="118rpx" :src="item.url" mode="aspectFill" border-radius="10">
					</u-image>
				</view>
			</template>

			<!-- 视频 -->
			<view class="uni-uploader__file" v-if="src">
				<view class="uploader_video" @click="actVideoPlay">
					<view @click.stop="delectVideo()" class="close-icon">
						<u-icon width="46" height="46" name="close-circle-fill" color="#fa3534" size="46"></u-icon>
					</view>
					<image class="uploader_video_play--icon" src="/static/images/home/play.png" mode="scaleToFill" />
					<u-image width="118rpx" height="118rpx" class="article-video_img" mode="widthFix"
						:src="VodImg+'?imageMogr2/crop/118x118/gravity/center'" v-if="!isPlay"></u-image>
				</view>
				<video id="video" :src="src" class="video" :autoplay="autoplay" @fullscreenchange="fullscreenchange"
					v-if="isPlay"></video>
			</view>
			<!-- 文件 -->
			<view class="u-m-t-20">
			  <view v-for="(item,index) in files.values()" :key="index" class="u-flex">
			  	<view class="color-blue u-font-30">{{ item.name}}</view>
			  	<u-line-progress active-color="#2979ff" :percent="item.progress" class="u-m-l-20" style="width:300rpx " v-if="item.progress < 100"></u-line-progress>
			  	<u-icon name="close-circle" @click.native="clear(item.name)" class="u-m-l-20" size="36" color="#989a9a"></u-icon>
			  </view>
			</view>
		</view>

		<view class="sync-check">
			<view class="sync-check-community">
				<u-checkbox @change="checkboxChange" v-model="item.checked" v-for="(item, index) in list" :key="index"
					:label="item.name" :name="item.id" v-if="index == 0"><text
						style="color:#248BFC">{{item.name}}</text>
				</u-checkbox>
			</view>

			<view class="sync-check-stat">
				<u-checkbox @change="checkboxChange" v-model="item.checked" v-for="(item, index) in list" :key="index"
					:label="item.name" :name="item.id" v-if="index > 0">{{item.name}}
				</u-checkbox>
			</view>
		</view>
		<view style="margin-left: 30rpx;color: #248BFC;" @click.stop="goKeepProjectItem">
			<u-icon name="list"></u-icon>{{' '}}{{ $t('mine.choose_repair')}}
		</view>
		<view style="margin-left: 30rpx;margin-top: 10rpx;color: #248BFC;" v-if="projectItem.ItemName !== undefined">
			{{projectItem.IndexNo}}{{' '}}{{projectItem.ItemName}}
		</view>
		<u-modal v-model="showModal" :title="this.$t('home.tip')"
			:content="this.$t('project.confirm_sync_bbs')" :show-cancel-button="true"
			:cancel-text="this.$t('project.btn_cancel')" :confirm-text="this.$t('project.btn_confirm')"
			@confirm="submit"></u-modal>
		<view class="publish-handle">
			<view class="publish-handle_content u-flex u-row-between">
				<view class="publish-handle_left u-flex">
						<view class="icon icon-biaoqing-expression1-01 u-m-r-20" @click.stop="actEmojiShow()" style="font-size:58rpx"></view>
					<text class="icon icon-tupian1" style="color: #464747" @click="isShowImagePicker = true"></text>
					<u-popup v-model="isShowImagePicker" mode="bottom">
						<view class="popup-item" @click="chooseImage('camera')">{{ $t('chat.shot') }}</view>
						<view class="popup-item" @click="chooseImage('album')">{{ $t('chat.choose_from_album')}}</view>
						<view class="divider"></view>
						<view class="popup-item" @click="isShowImagePicker = false">{{ $t('chat.chat_cancel') }}</view>
					</u-popup>
					<view class="u-m-l-30" @click.stop="isShowVideoPicker = true" v-show="JSON.parse(JSON.stringify(fileList)).length == 0">
						<text class="icon icon-video" style="font-size:54rpx;color: #7a7d7f"></text>
					</view>
					<u-popup v-model="isShowVideoPicker" mode="bottom">
						<view class="popup-item" @click="chooseVideo('camera')">{{ $t('chat.shot') }}</view>
						<view class="popup-item" @click="chooseVideo('album')">{{ $t('chat.choose_from_album')}}</view>
						<view class="divider"></view>
						<view class="popup-item" @click="isShowVideoPicker = false">{{ $t('chat.chat_cancel') }}</view>
					</u-popup>
					<view class="u-m-l-40">
						<lsj-upload
						ref="lsjUpload0"
						childId="upload1"
						:width="width"
						:height="height"
						:option="option"
						:size="size"
						:formats="formats"
						:debug="debug"
						:instantly="instantly"
						@change="onChange"
						@progress="onprogress"
						@uploadEnd="onuploadEnd"
						>
						<view class="icon icon-wenjianjiatianjia"></view>
						</lsj-upload>
					</view>
				</view>
				<view class="publish-handle_right">{{curlength}}/{{maxlength}}</view>
			</view>
			<view class="comment-box">
				<view v-if="emojiShow" class="TUI-Emoji-area">
					<TUI-Emoji @enterEmoji="appendMessage"></TUI-Emoji>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import TUIEmoji from "@/components/tui-chat/message-elements/emoji/index";
		import { parseText } from '@/utils/util.js';
	import {
    		emojiName,
    		emojiUrl,
    		emojiMap
    	} from "@/components/base/emojiMap";
  import pageMixin from '@/utils/pageMixin';
  import {db} from '@/utils/sqlite';
  import sqliteSQL from "@/utils/sqliteSQL";
  import store from '@/store/index.js';
	export default {
		mixins: [pageMixin],
		data() {
			return {
				userType: 2,
				project: 0,
				dkey: 0,
				iid: 0,
				form: {
					Type: 2
				},
				action: '',
				formData: {},

				publishButoonDisable: false,
				showUploadList: false,
				// 如果将某个ref的组件实例赋值给data中的变量，在小程序中会因为循环引用而报错
				// 这里直接获取内部的lists变量即可
				lists: [],
				fileList: [],
				maxlength: 1024,
				curlength: 0,
				src: "", //临时视频存放
				VodSrc: "", //线上视频地址
				VodImg: "",
				isPlay: false,
				autoplay: false,
				videoContext: null,
				list: [],
				checkBox: [],
				isSync: false,
				showModal: false,
				messageImages: [],
				messageVideos: [],
				checkGroupIds: [],

				projectItem: {},
				groupDict: [],
				option: {
					// 上传服务器地址，此地址需要替换为你的接口地址
					// url: 'http://hl.j56.com/dropbox/document/upload',
					url: 'https://tapi.i-dock.net/mgr/tool/upload/image',
					// 上传附件的key
					name: 'file',
					// 根据你接口需求自定义请求头,默认不要写content-type,让浏览器自适配
					header: {
						// 示例参数可删除
						'Authorization': 'bearer eyJhbGciOiJSUzI1NiIsI',
						'uid': '27682',
						'client': 'app',
						'accountid': 'DP',
					},
					// 根据你接口需求自定义body参数
					formData: {
						// 'orderId': 1000
						'catalog': 'cms'
					}
				},
				// 选择文件后是否立即自动上传，true=选择后立即上传
				instantly: true,
				// 必传宽高且宽高应与slot宽高保持一致
				width: '60rpx',
				height: '60rpx',
				// 限制允许上传的格式，空串=不限制，默认为空
				formats: '',
				// 文件上传大小限制
				size: 30,
				// 文件回显列表
				files: new Map(),
				// 微信小程序Map对象for循环不显示，所以转成普通数组，不要问为什么，我也不知道
				wxFiles: [],
				// 是否打印日志
				debug: true,
				tabIndex:0,
				emojiShow:false,
				cursorStart:0,  //输入框光标位置
				ctrPermission: 0,
				isShowImagePicker: false,  //显示上传图片弹出框
				isShowVideoPicker: false, // 显示上传视频弹出框                             
			}
		},
		onLoad(options) {
			this.userType = store.state.vuex_user.type || 2
			this.userUid = store.state.vuex_user.uid
			this.userAvatar = store.state.vuex_user.avatar
			this.userUname = store.state.vuex_user.uname
			this.form.Type = parseInt(options.type);
			this.project = options.project || 0;
			this.dkey = options.dkey || 0;
			this.iid = options.iid || 0;
			this.init();
			this.getPermissionContract()
			if (this.project > 0) {
				//打开SQLite数据库
				let dbname = sqliteSQL.db.dbName
				let path = '_doc/' + this.userUid + '.db'
				let isOpen = db.isOpenDB(dbname, path)
				if (!isOpen) {
					plus.sqlite.openDatabase({
						name: dbname,
						path: path,
						success: function(res) {
							console.log("打开成功")
						},
						fail: function(e) {
							console.log('failed: ' + JSON.stringify(e))
						}
					});
				}
				this.getProjectGroup();
			}
		},
		onShow() {
			uni.setNavigationBarTitle({
				title: this.$t('home.follow_post')
			})
			if (this.form.Type == 3) {
				setTimeout(() => {
					uni.setNavigationBarTitle({
						title: this.$t('home.contract_post')
					})
				}, 50);
			}

			uni.$on('checkItem', (item) => {
				this.checkedItem(item);
			})
		},
		// 只有onReady生命周期才能调用refs操作组件
		onReady() {
			// 得到整个组件对象，内部图片列表变量为"lists"
			this.fileList = this.$refs.uUpload.lists;
			this.messageImages = this.$refs.uUpload.resources;
			console.log("替换了图片", this.$refs.uUpload.resources);
		},
		mounted: function() {
			this.videoContext = uni.createVideoContext('video', this);
		},
		onUnload() {
		},
		onNavigationBarButtonTap(e) {
			if (e.type == 'close') {
				this.$u.route({
					type: 'back',
					delta: 1
				});
				return;
			}
			this.checkSyncCommunity();
		},
		components: {
		    TUIEmoji
		},
		computed: {
			// i18n() {
			// 	return this.$t('home')
			// },
			chat() {
				return this.$t('chat')
			}
		},
		methods: {
			init() {
				this.action = this.$store.state.fileUploadUrl
				this.formData = {
					catalog: 'cms'
				};
				this.list.push({
					name: this.$t('home.sync_community'),
					id: 0,
					checked: false,
					disabled: false
				});
			},
			connectGoEasy() {
				uni.showLoading();
				this.goEasy.connect({
					id: this.userUid,
					data: {
						name: this.userUname,
						avatar: this.userAvatar
					},
					onSuccess: () => {
						console.log('GoEasy connect successfully.')
					},
					onFailed: (error) => {
						console.log('Failed to connect GoEasy, code:' + error.code + ',error:' + error
							.content);
					},
					onProgress: (attempts) => {
						console.log('GoEasy is connecting', attempts);
					}
				});

				//订阅Goeasy消息
				this.goEasy.pubsub.subscribe({
					channel: "user" + this.userUid,
					onMessage: function(message) {
						console.log("Channel:" + message.channel + " content:" +
							message.content);
					},
					onSuccess: function() {
						console.log("Channel订阅成功。");
					},
					onFailed: function(error) {
						console.log("Channel订阅失败, 错误编码：" + error.code + " 错误信息：" +
							error.content)
					}
				});
			},
			checkedItem(item) {
				this.projectItem = item;
			},
			showImagePicker() {
			  this.isShowImagePicker = true
			},
			chooseImage(type) {
			  this.isShowImagePicker = false
				//判断是拍摄还是从相册中选择
				if(type == 'camera') {
					//拍摄
					uni.chooseImage({
						sourceType: ['camera'],
						success: (res)=> {
							// 上传图片
							uni.uploadFile({
								url: this.action,   // 自己文件上传的路径
								method:"POST",
								filePath: res.tempFilePaths[0],
								name: 'file',
								formData:{
									catalog:'cms'
								},
								success: res1=> {
									if(res1.statusCode == 200) {
										const file = JSON.parse(res1.data).data
										//给所选图片赋值
										this.fileList.push({
											url: file.domain + file.filepath,
											filepath: file.filepath
										})
										console.log(file.domain + file.filepath)
									}			
								}
						  })
					  },
					})
				}else {
					uni.chooseImage({
						sourceType: ['album'],
						success: res=> {
							res.tempFilePaths.forEach((item,index)=> {
								uni.uploadFile({
									url: this.action,   // 自己文件上传的路径
									method:"POST",
									filePath: item,
									name: 'file',
									formData:{
										catalog:'cms'
									},
									success: res1=> {
										if(res1.statusCode == 200) {
											const file = JSON.parse(res1.data).data
											//给所选图片赋值
											this.fileList.push({
												url: file.domain + file.filepath,
												filepath: file.filepath
											})
											console.log(file.domain + file.filepath)
										}			
									}
								})
							})
						}
					})
				}
			},
			actPreviewImage(e) {
				let index = e.currentTarget.dataset.index;
				let urls = [];
				this.fileList.forEach(function(item) {
					urls = urls.concat(item.url);
				});
				// 预览图片
				uni.previewImage({
					urls: urls,
					current: index,
					indicator: 'default',
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				});
			},
			deleteItem(index) {
				this.fileList.splice(index,1)
			},
			chooseVideo(type) {
				let that = this;
				if (that.src != '') {
					uni.showToast({
						title: this.$t('home.most_one_video'),
						icon: 'none'
					});
					return;
				}
        this.isShowVideoPicker = false
				// 上传视频
				uni.chooseVideo({
					maxDuration: 60,
					count: 1,
					camera: 'back',
					sourceType: [type],
					success: (res) => {
						uni.showLoading();
						uni.uploadFile({
							url: that.action, //上传接口地址
							filePath: res.tempFilePath,
							name: 'file',
							formData: {
								catalog: 'cms'
							},
							success: (uploadFileRes) => {
								console.log(uploadFileRes);
								var result = JSON.parse(uploadFileRes.data);
								that.VodSrc = result.data.filepath;
								that.src = res.tempFilePath;
								var arr = that.VodSrc.split('.');
								that.VodImg = result.data.domain + arr[0] + '_0.jpg';
								that.messageVideos.push(res),

									// 按实际上传的视频回调地址显示
									// that.src = result.data.domain+result.data.filepath;
									uni.hideLoading();
							},
							complete: res => {
								uni.hideLoading();
							}
						});
					}
				})
			},
			actVideoPlay() {
				this.isPlay = true;
				this.autoplay = true;
				setTimeout(()=> {
					this.videoContext.requestFullScreen({direction:'0'});
				},100)	
			},
			fullscreenchange(e) {
				if (!e.detail.fullScreen) {
					this.isPlay = false;
				}
			},
			delectVideo: function() {
				uni.showModal({
					title: this.$t('home.tip'),
					content: this.$t('home.del_video'),
					success: (res) => {
						if (res.confirm) {
							this.src = '';
							this.VodSrc = '';
							this.VodImg = '';
						}
					}
				})
			},
			checkboxChange(e) {
				//检查是否勾选同步社区
				if (e.value && e.name == 0) {
					this.isSync = true;
				} else if (!e.value && e.name == 0) {
					this.isSync = false;
				}

				//检查是否勾选同步群聊
				if (e.value && e.name > 0) {
					this.checkGroupIds[e.name] = 1;
				} else if (!e.value && e.name > 0) {
					if (this.checkGroupIds[e.name] !== undefined) {
						delete this.checkGroupIds[e.name];
					}
				}
			},
			getProjectGroup() {
				let that = this,
					lang = '';
				lang = that.$t('home.sync_group');
				that.$http.get('/mgr/user/group/list/data', {
					pid: that.project
				}).then(function(res) {
					for (let i = 0; i < res.length; i++) {
						let name = res[i].GroupName;
						that.list.push({
							name: lang + name,
							id: res[i].Gid,
							checked: false,
							disabled: false
						});
						that.groupDict[res[i].Gid] = res[i];
					}
				});
			},
			checkSyncCommunity() {
				let that = this;
				let ImgPack = [];
				this.fileList.forEach(function(item) {
					ImgPack.push({
						src: item.filepath,
					});
				});
				this.form.ImgPack = JSON.stringify(ImgPack);
				if (this.project > 0) {
					this.form.Project = parseInt(this.project);
				}
				if (this.dkey > 0) {
					this.form.Demand = parseInt(this.dkey);
				}
				if (this.iid > 0) {
					this.form.Item = parseInt(this.iid);
				}
				this.form.VodSrc = that.VodSrc;
				//定义上传后的文件,以便给form中AttPack赋值
				var fileList = []
					this.files.forEach((val,key)=>{
						if(typeof val.responseText == 'string') {
							val.responseText = JSON.parse(val.responseText)
						}
						console.log(val.responseText.data)
						fileList.push({
							name: val.name,
							src: val.responseText.data.domain + val.responseText.data.filepath
						})
					})
					this.form.AttPack = JSON.stringify(fileList)
				  if (this.form.Content == '' || this.form.Content == undefined && ImgPack.length == 0 && this.VodSrc ==
					'' && (this.form.AttPack == '' || this.form.AttPack == '[]')) {
					uni.showToast({
						title: this.$t('home.pub_tips') + '~',
						icon: 'none'
					});
					return;
				}
				this.form.isSync = this.isSync;
				if (this.isSync) {
					this.showModal = true
					return
				}

				this.submit()
			},
			parseText,
			submit() {
				console.log('进来----------------------------------------------------')
				let that = this
				if (that.publishButoonDisable) {
					uni.showToast({
						title: '发送中...',
						icon: 'none',
					});
					 return
				}
				console.log('sdsdsfsdf---------------')
				that.publishButoonDisable = true;
				that.form.Item = that.projectItem.Iid || 0;
				if (that.form.Item == 0) {
					that.form.Item = parseInt(that.iid);
				}
				console.log('sdsdsfsdf---------------')
				//解析回复内容拼重新拼接回复内容
				let newContent = '';
				console.log('this.form.Content=--------------',this.form.Content)
				if(this.form.Content != undefined) {
					console.log('sdsdsfsdf---------------')
					let content = this.parseText(that.form.Content);
					for (let i = 0; i < content.length; i++) {
						if (content[i].name == 'img') {
							newContent += '<img style="width:20px;height:20px;vertical-align: text-bottom;display: inline-block" src="' + content[i].src +
								'"></img>';
						} else if (content[i].name == 'span') {
							newContent += content[i].text;
						}

					}
				}

				// 新定义临时变量用于存放form对象,给临时变量中的content重新赋值,避免this.form.Content发生变化影响页面观赏效果
				let form = JSON.parse(JSON.stringify(this.form))
				form.Content = newContent;
				console.log(form)

					console.log('dsadsfsdfdsf')
					that.$http.post('/bbs/topic/save',form, that.jHeader).then(res => {

						that.publishButoonDisable = false;
						uni.showToast({
							title: that.$t('home.pub_success'),
						});
						//检查是否同步群聊
						for (var gid in that.checkGroupIds) {
							console.log("进来发消息了大哥")
							that.sendTextMessage(gid);
							that.sendImageMessage(gid);
							that.sendVideoMessage(gid);
						}

						setTimeout(() =>{
						  uni.navigateBack({
							  delta: 1
						  })
						}, 500);
					}).catch(err => {
						that.publishButoonDisable = false;
					});
			},
			actInput(e) {
				this.curlength = e.detail.cursor;
				if (this.curlength >= this.maxlength) {
					uni.showToast({
						title: '最多输入' + this.maxlength + '个字',
						icon: 'none'
					});
				}
			},
			getPermissionContract() {
				let that = this;
				that.$http.get('/client/biz/project/item/permission/contract', {
					project: that.project
				}).then(res => {
					this.ctrPermission = res
				});
			},
			sendTextMessage(gid) {
				let text = this.form.Content || '';
				console.log("text", text);
				console.log("进来发了");
				if (text != '') {
					let body = text;
					if (text.length >= 50) {
						body = text.substring(0, 30) + '...';
					}
					console.log("this.groupDict", this.groupDict);
					console.log("this.groupDict[gid].GroupName", this.groupDict[gid]);
					let textMessage = this.goEasy.im.createTextMessage({
						text: text,
						to: {
							id: gid,
							type: this.GoEasy.IM_SCENE.GROUP,
							data: {
								name: this.groupDict[gid].GroupName || '',
								avatar: this.groupDict[gid].GroupAvatar != '' ? this.groupDict[gid].GroupAvatar :
									'/static/static/assets/gruopavatar.svg'
							}
						},
						notification: {
							title: this.userUname + this.chat.chat_send_text,
							body: body
						}
					});
					this.$sendTIMMessage(textMessage);
				}
			},
			sendImageMessage(gid) {
				console.log("this.messageImages", this.messageImages);
				for (var i = 0; i < this.messageImages.length; i++) {
					let imageMessage = this.goEasy.im.createImageMessage({
						to: {
							id: gid,
							type: this.GoEasy.IM_SCENE.GROUP,
							data: {
								name: this.groupDict[gid].GroupName || '',
								avatar: this.groupDict[gid].GroupAvatar != '' ? this.groupDict[gid].GroupAvatar :
									'/static/static/assets/gruopavatar.svg'
							}
						},
						file: this.messageImages[i],
						onProgress: function(progress) {
							console.log(progress)
						},
						notification: {
							title: this.userUname + this.chat.chat_send_image,
							body: '[' + this.chat.chat_image_message + ']' // 字段最长 50 字符
						}
					});
					console.log("到这里来了");
					this.$sendTIMMessage(imageMessage);
				}
			},
			sendVideoMessage(gid) {
				for (var i = 0; i < this.messageVideos.length; i++) {
					let videoMessage = this.goEasy.im.createVideoMessage({
						to: {
							id: gid,
							type: this.GoEasy.IM_SCENE.GROUP,
							data: {
								name: this.groupDict[gid].GroupName || '',
								avatar: this.groupDict[gid].GroupAvatar != '' ? this.groupDict[gid].GroupAvatar :
									'/static/static/assets/gruopavatar.svg'
							}
						},
						file: this.messageVideos[i],
						onProgress: function(progress) {
							console.log(progress)
						},
						notification: {
							title: this.userUname + this.chat.chat_send_video,
							body: '[' + this.chat.chat_video_message + ']' // 字段最长 50 字符
						}
					});
					this.$sendTIMMessage(videoMessage);
				}
			},

			downloadMessageFile(url, messageId, key) {
				let that = this
				console.log("下载消息的图片", url)
				if (url != '' && url.indexOf('http') == 0) {
					uni.downloadFile({
						url: url,
						success: (res) => {
							if (res.statusCode === 200) {
								uni.saveFile({
									tempFilePath: res.tempFilePath,
									success: function(result) {

										console.log("下载好了", result.savedFilePath)
										//更新消息数据
										that.updateSQLiteMessageData(messageId, result
											.savedFilePath, key, table)
									},
								})
							}
						}
					})
				} else if (url != '') {
					uni.saveFile({
						tempFilePath: url,
						success: function(result) {
							console.log("前面的地址", url)
							console.log("下载厚的地址", result.savedFilePath)
							console.log("保存的地址", key)
							//更新消息数据
							that.updateSQLiteMessageData(messageId, result.savedFilePath, key, table)
						},
					})
				}
			},
			insertSQLiteMessageData(insertData) {
				let dbname = sqliteSQL.db.dbName
				let path = '_doc/' + this.userUid + '.db'

				//打开数据库
				let isOpen = db.isOpenDB(dbname, path)
				if (isOpen) {
					plus.sqlite.executeSql({
						name: dbname,
						sql: insertData,
						success: (e) => {
							console.log("历史消息新增成功", e);
						},
						fail: (e) => {
							console.log("历史消息新增失败", e);
						}
					})
				}
			},
			updateSQLiteMessageData(messageId, url, key) {

				let dbname = sqliteSQL.db.dbName
				let path = '_doc/' + this.userUid + '.db'
				let updateSql = `UPDATE im_conversation_message SET ${key} = "${url}" WHERE message_id = "${messageId}";`

				console.log("updateSql", updateSql)

				//打开数据库
				let isOpen = db.isOpenDB(dbname, path)
				if (isOpen) {
					plus.sqlite.executeSql({
						name: dbname,
						sql: updateSql,
						success: (e) => {
							console.log("消息图片更新成功", e);
						},
						fail: (e) => {
							console.log("消息图片更新失败", e);
						}
					})
				}
			},
			$sendTIMMessage(message) {
				console.log("进来发送了");
				console.log("message", message);

				let that = this
				let messageId = message.messageId
				let senderData = message.senderData || {}
				let video = message.payload.video || {}
				let thumbnail = message.payload.thumbnail || {}
				let payloadUrl = message.payload.url || ''
				let videoUrl = video.url || ''
				let thumbnailUrl = thumbnail.url || ''
				let insertData = []

				let data = {
					'message_id': message.messageId,
					'receiver_id': this.userUid,
					'sender_id': message.senderId,
					'sender_name': senderData.name || '',
					'sender_avatar': senderData.avatar || '',
					'timestamp': message.timestamp,
					'message_type': message.type,
					'message_recalled': message.recalled ? 1 : 0,
					'message_status': message.status,
					'message_read': message.read ? 1 : 0,
					'payload_text': message.payload.text || '',
					'payload_name': message.payload.name || '',
					'payload_content_type': message.payload.contentType || '',
					'payload_url': payloadUrl,
					'payload_duration': message.payload.duration || '',
					'payload_size': message.payload.size || '',
					'payload_width': message.payload.width || '',
					'payload_height': message.payload.height || '',
					'video_name': video.name || '',
					'video_content_type': video.contentType || '',
					'video_url': videoUrl,
					'video_duration': video.duration || '',
					'video_width': video.width || '',
					'video_height': video.height || '',
					'video_size': video.size || '',
					'thumbnail_content_type': thumbnail.contentType || '',
					'thumbnail_url': thumbnailUrl,
					'thumbnail_width': thumbnail.width || '',
					'thumbnail_height': thumbnail.height || '',
					'payload_video_url': message.payload.videoUrl || '',
					'payload_thumbnai_url': message.payload.thumbnailUrl || '',
					'payload_path': message.payload.path || '',
				};
				console.log("data", data)
				let keys = Object.keys(data)
				console.log("keys", keys)
				let keyStr = keys.toString()
				console.log("keyStr", keyStr)
				let valStr = ''
				for (let key in data) {
					valStr += ('"' + data[key] + '",')
				}
				valStr = valStr.substr(0, valStr.length - 1);
				console.log("valStr", valStr)
				let sqlStr = `INSERT INTO im_conversation_message(${keyStr}) values(${valStr})`
				insertData.push(sqlStr)

				console.log("发送给的消息啊", data)

				this.goEasy.im.sendMessage({
					message: message,
					onSuccess: function(message) {
						console.log('发送成功.', message);

						that.insertSQLiteMessageData(insertData)
						let thumbnail = message.payload.thumbnail || {}
						data.thumbnail_url = thumbnail.url
						//下载图片、视频、音频到本地
						that.downloadMessageFile(payloadUrl, messageId, 'payload_url')
						that.downloadMessageFile(videoUrl, messageId, 'video_url')
						that.downloadMessageFile(message.payload.thumbnail.url || '', messageId,
							'thumbnail_url')
						that.downloadMessageFile(senderData.avatar || '', messageId, 'sender_avatar')
					},
					onFailed: function(error) {
						if (error.code === 507) {
							console.log(
								'发送语音/图片/视频/文件失败，没有配置OSS存储，详情参考：https://www.goeasy.io/cn/docs/goeasy-2.x/im/message/media/send-media-message.html'
							);
						} else {
							console.log('发送失败:', error);
						}
					}
				});
			},
			goKeepProjectItem() {
				uni.navigateTo({
					url: '/pages/repair/project_item/index?project=' + this.project
				});
			},
			onuploadEnd(item) {
				console.log(`${item.name}已上传结束，上传状态=${item.type}`);

				// 更新当前状态变化的文件
				this.files.set(item.name,item);

				// 演示上传完成后取服务端数据
				if (item['responseText']) {
					console.log('演示服务器返回的字符串JSON转对象');
					this.files.get(item.name).responseText = JSON.parse(item.responseText);
				   console.log(this.files.get(item.name).responseText)
				}
				console.log(this.files.values)

				// 微信小程序Map对象for循环不显示，所以转成普通数组，不要问为什么，我也不知道
				// #ifdef MP-WEIXIN
				this.wxFiles = [...this.files.values()];
				// #endif

				// 强制更新视图
				this.$forceUpdate();


				// ---可删除--演示判断是否所有文件均已上传成功
				let isAll = [...this.files.values()].find(item=>item.type!=='success');
				if (!isAll) {
					console.log('已全部上传完毕');
				}
				else {
					console.log(isAll.name+'待上传');
				}

			},
			// 上传进度回调
			onprogress(item) {
				// 更新当前状态变化的文件
				this.files.set(item.name,item);
				console.log(this.files.values())
				console.log('打印对象',JSON.stringify(this.files.get(item.name)));
				// 微信小程序Map对象for循环不显示，所以转成普通数组，不要问为什么，我也不知道
				// #ifdef MP-WEIXIN
				this.wxFiles = [...this.files.values()];
				// #endif

				// 强制更新视图
				this.$forceUpdate();

			},
			// 文件选择回调
			onChange(files) {
				// 更新选择的文件
				this.files = files;
				// 强制更新视图
				this.$forceUpdate();

				// 微信小程序Map对象for循环不显示，所以转成普通数组，不要问为什么，我也不知道
				// #ifdef MP-WEIXIN
				this.wxFiles = [...this.files.values()];
				// #endif
			},
			// 手动上传
			upload() {
				// name=指定文件名，不指定则上传所有type等于waiting和fail的文件
				this.$refs['lsjUpload'+this.tabIndex].upload();
			},
			// 移除某个文件
			clear(name) {
				// name=指定文件名，不传name默认移除所有文件
				this.$refs['lsjUpload'+this.tabIndex].clear(name);
			},
			//小表情
			actEmojiShow() {
				if (this.emojiShow) {
					this.emojiShow = false;
				} else {
					this.emojiShow = true;
				}
			},
			textblur(e) {
				this.cursorStart = e.detail.cursor
			},
			appendMessage(e) {
        if(this.form.Content !== undefined){
        	this.form.Content = this.form.Content.slice(0,this.cursorStart) + e.detail.message + this.form.Content.slice(this.cursorStart);
        }else{
        	this.$set(this.form,'Content',e.detail.message)
        }
        this.isSend = false;
      },
		}
	}
</script>

<style lang="scss" scoped>
	.publish {
		box-sizing: border-box;
		padding-bottom: 100rpx;
		min-height: 100vh;
		background-color: #fff;

		&-input {
			padding: 30rpx;
			width: 100%;
		}
	}

	.publish-images {
		padding: 0 30rpx;
		margin-bottom: 30rpx;
		clear: both;
		overflow: hidden;

		&_item {
			position: relative;
			margin: 10rpx;
			float: left;

			.u-icon {
				z-index: 999;
				position: absolute;
				top: 6rpx;
				right: 6rpx;
				background-color: #FFFFFF;
				border-radius: 42px;
			}
		}
	}

	.uploader_video {
		position: relative;
		width: 118rpx;
		height: 118rpx;
		border-radius: 10rpx;
		overflow: hidden;

		.close-icon {
			z-index: 99999;
			position: absolute;
			top: 4rpx;
			right: 4rpx;

			.u-icon {
				background: #FFFFFF ;
				border-radius: 100%;
			}
		}

		&_play--icon {
			width: 36rpx;
			height: 36rpx;
			z-index: 999;
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%, -50%);
			border-radius: 5px;
			background: #505050;
		}
	}

	.publish-handle {
		z-index: 999;
		width: 100%;
		position: fixed;
		left: 0;
		bottom: 0;
		background-color: #f1f1f1;

		&_content {
			padding: 20rpx 30rpx;
			border-bottom: 1px solid #d7dada;
		}

		&_left {
			font-size: 48rpx;
			color: #777777;

			&--item {
				padding: 0 40rpx;
			}

			.icon {
				font-size: 48rpx;
				// margin-right: 20rpx;
			}
			.popup-item {
				width: 100%;
				height: 100rpx;
				line-height: 100rpx;
				background-color: #fff;
				text-align: center;
				color: #545555;
				font-size: 32rpx;
				border-bottom: 1px solid #e9ecec;
			}
			.divider {
				width: 100%;
				height: 20rpx;
				background-color: rgba(0,0,0,0.6);
			}
		}

		&_right {
			color: #999999;
		}
	}
.color-blue{
		color: #0089FF;
	}
	.sync-check {
		padding: 0 30rpx;
		margin-bottom: 100rpx;
		margin-top: 400rpx;

		.sync-check-stat {
			margin-top: 30rpx;
		}
	}
	.comment-box {
		padding-right: 20rpx;
		padding-left:20rpx;
		background-color: #fff;
	}
</style>
